<?php
namespace Admin\Controller;
use Think\Controller;
class LoginController extends Controller {

    /**
     * 验证码
     */
    public function verify(){
        $Verify = new \Think\Verify();
        $Verify->useImgBg = false;  //不设置背景图片
        $Verify->imageW = 180;
        $Verify->imageH = 50;
        $Verify->length = 4;
        $Verify->entry();
    }

    /**
     * 注销
     */
    public function logout(){
        session(null);
        $this->success('注销成功',U('Login/index'));
    }

    public function index(){
        if(IS_POST){
            //TODO: 优化:这段可以加进AdminUserModel里面。
            $rules = array(
                array('verify','require','验证码必须！'),
                array("username",'/^[a-zA-Z][a-zA-Z0-9]{3,19}$/','用户名必须以字母开头，由4~20位数字与字母组成'),
                array("password",'/^[a-zA-Z0-9]{6,20}$/','密码必须由6~20字母数字组成'),
            );

            $AdminUser = M("AdminUser"); // 实例化User对象
            if (!$AdminUser->validate($rules)->create()){
                $this->error($AdminUser->getError());
            }else{
                // 验证通过 可以进行其他数据操作
                if(!check_verify(I('post.verify'))){
                    $this->error('验证码错误');
                }

                $wh['username'] = I('post.username');
                $password = I('post.password');
                $arrOne = M('AdminUser')->field('id,password')->where($wh)->find();
                if($arrOne && $arrOne['password'] == $password ){
                    session('lh_uid',$arrOne['id']);
                    session('lh_uname',$wh['username']);
                    if(I('post.remember') == 1){
                        cookie('remember','1',array('expire'=>3600*7*24,'prefix'=>'lh_'));
                        cookie('username',$wh['username'],array('expire'=>3600*7*24,'prefix'=>'lh_'));
                        cookie('password',$password,array('expire'=>3600*7*24,'prefix'=>'lh_'));
                    }else{
                        cookie(null,'lh_'); // 清空指定前缀的所有cookie值
                    }
                    $this->success('登录成功',U('Index/index'));
                }else{
                    session(null);
                    $this->error('用户名或密码错误');
                }
            }
        }else{
            layout(false); //关闭模板布局
            $this->display();
        }
    }



}